package com.greensoftcodeplus.sqllog.component;




import com.greensoftcode.MyFun;
import com.greensoftcodeplus.sqllog.properties.MySqlPropertiesLog;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;


import java.text.DateFormat;
import java.util.*;
import java.util.regex.Matcher;

@Intercepts(
        {
                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
                @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        }
)
public class MybatisLogInterceptor implements Interceptor {
    MySqlPropertiesLog myProperties;

    public MybatisLogInterceptor(MySqlPropertiesLog myProperties) {
        this.myProperties = myProperties;
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        if (myProperties.isMySqlEnable() ) {
            try {
                Object[] args = invocation.getArgs();
                MappedStatement ms = (MappedStatement) args[0];
                Object params = args[1];
                Configuration configuration = ms.getConfiguration();
                BoundSql boundSql = ms.getSqlSource().getBoundSql(params);    //getBoundSql(params) 获得整个sql  因为params可能包括子sql作为参数${}传递
                String sqlId = ms.getId();
                //获取真实的sql语句
                String sql = getSql(configuration, boundSql, sqlId, 0);
                sql = "=======================SqlLogPlus拦截sql================\r\n" + sql + "\r\n" + "=====================================================\r\n";
                System.out.println(sql);
                String mySqlLogpath = myProperties.getMySqlLogpath();
                String mySqlLogfilename = myProperties.getMySqlLogfilename();
                MyFun.myLogFileOnlyDays(mySqlLogpath, mySqlLogfilename, sql,myProperties.getMyOnlyDays());

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return invocation.proceed();
    }



    private static String getParameterValue(Object obj) {
        String value = null;
        if (obj instanceof String) {
            value = "'" + obj.toString() + "'";
        } else if (obj instanceof Date) {
            DateFormat formatter = DateFormat.getDateTimeInstance(
                    DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
            value = "'" + formatter.format(obj) + "'";
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
            }

        }
        return value;
    }

    private static String showSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        if (!parameterMappings.isEmpty() && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration
                    .getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?",
                        Matcher.quoteReplacement(getParameterValue(parameterObject)));

            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        Object obj = boundSql
                                .getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                    } else {
                        sql = sql.replaceFirst("\\?", "无法匹配参数值");
                    }//打印出缺失，提醒该参数缺失并防止错位
                }
            }
        }
        return sql;
    }
    private static String getSql(Configuration configuration, BoundSql boundSql,
                                 String sqlId, long time) {
        String sql = showSql(configuration, boundSql);
        StringBuilder str = new StringBuilder(100);
//        str.append(sqlId);
//        str.append(":");
        str.append(sql);
        return str.toString();
    }
    @Override
   public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }


}
